#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import cgi
import datetime
import os
import lib
import logging
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext import db
from google.appengine.api import datastore_errors
from google.appengine.ext.webapp import template
from lib import llhandler
from model.models import *
class ListAreasHandler(llhandler.PSHandler):
	
	
	def internal_get(self):
		#You can see all the projects from YOUR company
		
		self.add("areas",self.user.company.areas)
		self.add("company",self.user.company)
		self.render('areas_list')
		
	
	def internal_post(self):
		self.internal_get()


class CreateProjectHandler(llhandler.PSHandler):
  
	def get(self,wf_id):
	  self.auth_check()
	  self.internal_get(wf_id)
	
	def post(self,wf_id):
	  self.auth_check()
	  self.internal_post(wf_id)
	
	def internal_get(self,wf_id):
	  wf = PSWorkflow.get_by_id(int(wf_id))
	  if wf is None:
	    self.set_flash("Non existing workflow")
	    self.redirect("/workflows/")
	    return
	  self.add('workflow',wf)
	  self.render('request_new')
	  
	def internal_post(self,wf_id):
	  wf = PSWorkflow.get_by_id(int(wf_id))
	  if wf is None:
	    self.set_flash("Non existing workflow")
	    self.redirect("/workflows/")
	    return
	  
	  try:
	    
	    psrequest = PSRequest(comment=self.request.get('comment'),status="pending")
	    psrequest.requestor = self.user
	    psrequest.workflow = wf
	    psrequest.name = self.request.get('name')
	    psrequest.origin = self.request.get('origin')
	    psrequest.destination = self.request.get('destination')
	    psrequest.files_changed = self.request.get_all('files_changed_values')
	    psrequest.required_commands = self.request.get_all('required_commands_values')
	    
	    psrequest.put()
	    self.prepare_request_for_workflow(psrequest,wf)
	  except Exception, e:
	    self.set_flash('Could not create request:' + str(e),'error')
	    self.internal_get(wf_id)
	    return
	  self.set_flash('Request Successfully created');
	  self.redirect('/requests/'+str(psrequest.key().id()))
	 
	def prepare_request_for_workflow(self,request,workflow):
	  
	  elements = workflow.elements.order('priority')
	  #elements.sort(cmp=lambda x,y: cmp(x.priority,y.priority))
	  for element in elements:
	    step = PSStep()
	    step.workflow_element = element
	    step.request = request
	    step.put()
	    request.pending_steps.append(step.key())
	  request.put()
	  
class AddMemberToProjectHandler(llhandler.PSHandler):
  
      def post(self,project_key):
	self.auth_check()
	self.internal_post(project_key)
	
      def internal_post(self,project_key):
	project = PSProject.get(db.Key(encoded=project_key))
	member = PSUser.get(db.Key(encoded=self.request.get('member_key')))
	if member.key() in project.members:
	  self.set_flash(member.name + ' is already member of this project','info')
	  self.redirect('/projects/'+str(project.key()))
	  return
	if self.user.key() == project.leader.key():
	  try:
	    project.members.append(member.key())
	    member.projects.append(project.key())
	    project.put()
	    member.put()
	    self.set_flash(member.name + ' has been added to the project')
	  except Exception,e:
	    self.set_flash('There was a problem adding user to project: ' + str(e))
	else:
	  self.set_flash('Member cannot be added, user is not project leader','error')
	  
	self.redirect('/projects/'+str(project.key()))
	
class ShowAreaHandler(llhandler.PSHandler):
	
	def get(self,area_key):
	  self.auth_check()
	  self.internal_get(area_key)
	  
	def internal_get(self,area_key):
		area = PSArea.get(db.Key(encoded=area_key))
		responsibles= PSUser.get(area.responsibles)
		projects = area.projects
		a = set([self.logged_user.key()])
		b =set(area.responsibles)
		c = a.intersection(b)
		l = list(c)
		logging.debug("Set logged user :" + str(a))
		logging.debug("Set responsibles:" + str(b))
		logging.debug("Intersection    :" + str(c))
		logging.debug("List            :" + str(l))
		logging.debug("Length          :" + str(len(l)))
		
		#By now, only project leaders can add members
		self.add("area",area)
		self.add('can_add_projects',len(l) > 0)
		self.add('projects',projects)
		self.add('responsibles',responsibles)
		self.render('area_show')


def main():
  logging.getLogger().setLevel(logging.DEBUG)
  application = webapp.WSGIApplication([('/projects/(\S+)/add_member',AddMemberToProjectHandler),
					('/areas/(\S+)', ShowAreaHandler),
					('/areas/', ListAreasHandler)],
                                       debug=True)
  util.run_wsgi_app(application)


if __name__ == '__main__':
  main()
